package com.lk.car.service.impl;

import com.lk.basic.util.PageList;
import com.lk.car.es.doc.CarDoc;
import com.lk.car.es.repository.CarDocRepository;
import com.lk.car.query.CarSearchQuery;
import com.lk.car.service.ICarSearchService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class CarSearchServiceImpl implements ICarSearchService {

    @Autowired
    private CarDocRepository carDocRepository;
    @Override
    public PageList search(CarSearchQuery query) {
        //创建Query对象
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //2高级查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //2.1关键词查询
        if (StringUtils.isNotBlank(query.getKeyword())){
            boolQuery.must(QueryBuilders.multiMatchQuery(query.getKeyword(),"title","shopName","typeName","carInfo"));
        }
        //2.2过滤查询
        //typeId;//类型id
        Long typeId=query.getTypeId();
        //costeffective;//是否超值
        Integer costeffective=query.getCosteffective();
        //rushsale;//是否急售
        Integer rushsale=query.getRushsale();
        //quasinewcar;//是否准新车
        Integer quasinewcar=query.getQuasinewcar();
        //transitivecountry;//是否可迁全国
        Integer transitivecountry=query.getTransitivecountry();
        if (typeId!=null){
            boolQuery.filter(QueryBuilders.termQuery("typeId",typeId));
        }
        if (costeffective!=null){
            boolQuery.filter(QueryBuilders.termQuery("costeffective",costeffective));
        }
        if (rushsale!=null){
            boolQuery.filter(QueryBuilders.termQuery("rushsale",rushsale));
        }
        if (quasinewcar!=null){
            boolQuery.filter(QueryBuilders.termQuery("quasinewcar",quasinewcar));
        }
        if (transitivecountry!=null){
            boolQuery.filter(QueryBuilders.termQuery("transitivecountry",transitivecountry));
        }
        //价格
        BigDecimal minPrice = query.getMinPrice();//最低价
        BigDecimal maxPrice = query.getMaxPrice();//最高价
        if (minPrice!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("costprice").gte(minPrice));
        }
        if (maxPrice!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("costprice").lte(maxPrice));
        }
        //车龄
        Integer carAge = query.getCarAge();
        Integer carAgeType = query.getCarAgeType();
        if (carAge!=null || carAgeType !=null){
            carAge=0-carAge;
            Date date = DateUtils.addYears(new Date(), carAge);
            if (carAgeType==0){
                boolQuery.filter(QueryBuilders.rangeQuery("reigstertime").gte(date));
            }else {
                boolQuery.filter(QueryBuilders.rangeQuery("reigstertime").lte(date));
            }
        }

        builder.withQuery(boolQuery);
        //排序查询
        String sortField = query.getSortField();//jg/cl
        String sortType = query.getSortType();
        SortOrder sortOrder= SortOrder.DESC;
        if ("asc".equals(sortType)){
            sortOrder=SortOrder.ASC;
        }
        if ("jg".equals(sortField)){
            builder.withSort(SortBuilders.fieldSort("costprice").order(sortOrder));
        }
        if ("cl".equals(sortField)){
            builder.withSort(SortBuilders.fieldSort("carage").order(sortOrder));
        }
        if ("lc".equals(sortField)){
            builder.withSort(SortBuilders.fieldSort("mileage").order(sortOrder));
        }
        if ("publish".equals(sortField)){
            builder.withSort(SortBuilders.fieldSort("publishtime").order(sortOrder));
        }


        //分页
        builder.withPageable(PageRequest.of(query.getStart(),query.getPageSize()));

        // 5 高亮查询
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");    // 要高亮展示的字段
        highlightBuilder.preTags("<span style=\"color:red;\">");    // 配置关键字前后的标签
        highlightBuilder.postTags("</span>");
        builder.withHighlightBuilder(highlightBuilder);
        //调用search方法到ES中查询，封装PageList方法
        Page<CarDoc> carDocs = carDocRepository.search(builder.build());
        List<CarDoc> content = carDocs.getContent();
        for (CarDoc doc : content) {
            String shopAddress=doc.getShopAddress();
            if (StringUtils.isNoneBlank(shopAddress)){
                doc.setShopAddress(shopAddress.split("市")[0]);
            }
        }
        long total = carDocs.getTotalElements();
        return new PageList(total,content);
    }
}
